﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Net.Share;
using Net.System;
using Net.Helper;
using Debug = Net.Event.NDebug;

namespace Net.Server
{
    /// <summary>
    /// TCP服务器类型
    /// 第四版本 2025.2.7
    /// </summary>
    public class TcpServer<Client> : ServerBase<Client> where Client : ClientPeer, new()
    {
        protected FastList<Socket> acceptList = new();

        protected override void StartProcessAccept()
        {
            var thread = new Thread(ProcessAccept)
            {
                IsBackground = true,
                Name = "ProcessAccept"
            };
            thread.Start();
            ServerThreads.Add("ProcessAccept", thread);
        }

        protected override void CreateServerSocket(int port)
        {
            try
            {
                var address = new IPEndPoint(IPAddress.Any, port);
                Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                {
                    SendBufferSize = Config.SendBufferSize,
                    ReceiveBufferSize = Config.ReceiveBufferSize,
                    NoDelay = true
                };
                Server.Bind(address);
                Server.Listen(Config.OnlineLimit + Config.LineUp);
            }
            catch (Exception ex)
            {
                Debug.LogError($"监听{port}端口异常:{ex}");
            }
        }

        protected virtual void ProcessAccept()
        {
            while (IsRunServer)
            {
                AcceptUpdate();
            }
        }

        protected void AcceptUpdate(bool isSleep = true)
        {
            try
            {
                if (Server.Poll(performance, SelectMode.SelectRead))
                {
                    var socket = Server.Accept();
                    socket.ReceiveTimeout = (int)Config.ReconnectionTimeout;
                    acceptList.Add(socket);
                }
                else if (isSleep) Thread.Sleep(1);
                CheckAcceptList(acceptList);
            }
            catch (Exception ex)
            {
                Debug.LogError($"接受异常:{ex}");
            }
        }

        protected void CheckAcceptList(FastList<Socket> acceptList)
        {
            Socket client;
            for (int i = 0; i < acceptList.Count; i++)
            {
                client = acceptList[i];
                if (!client.Connected)
                {
                    client.Close();
                    acceptList.RemoveAt(i);
                    continue;
                }

                if (!client.Poll(performance, SelectMode.SelectRead))
                    continue;
                using (var segment = BufferPool.Take(Config.ReceiveBufferSize))
                {
                    segment.Count = client.Receive(segment.Buffer, 0, segment.Length, SocketFlags.None, out var error);
                    if (segment.Count == 0 | error != SocketError.Success) //当等待10秒超时
                    {
                        client.Close();
                        acceptList.RemoveAt(i);
                        continue;
                    }

                    CheckReconnect(client, segment);
                    acceptList.RemoveAt(i);
                }
            }
        }
    }

    public class TcpServer<Client, Scene> : ServerBase<Client, Scene>
        where Client : ClientPeerBase, new()
        where Scene : SceneBase<Client>, new()
    {
        protected override void StartProcessAccept()
        {
            var thread = new Thread(ProcessAccept)
            {
                IsBackground = true,
                Name = "ProcessAccept"
            };
            thread.Start();
            ServerThreads.Add("ProcessAccept", thread);
        }

        protected override void CreateServerSocket(int port)
        {
            try
            {
                var address = new IPEndPoint(IPAddress.Any, port);
                Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                {
                    SendBufferSize = Config.SendBufferSize,
                    ReceiveBufferSize = Config.ReceiveBufferSize,
                    NoDelay = true
                };
                Server.Bind(address);
                Server.Listen(Config.OnlineLimit + Config.LineUp);
            }
            catch (Exception ex)
            {
                Debug.LogError($"监听{port}端口异常:{ex}");
            }
        }

        protected virtual void ProcessAccept()
        {
            var acceptList = new FastList<Socket>();
            while (IsRunServer)
            {
                try
                {
                    if (Server.Poll(performance, SelectMode.SelectRead))
                    {
                        var socket = Server.Accept();
                        socket.ReceiveTimeout = (int)Config.ReconnectionTimeout;
                        acceptList.Add(socket);
                    }
                    else Thread.Sleep(1);

                    CheckAcceptList(acceptList);
                }
                catch (Exception ex)
                {
                    Debug.LogError($"接受异常:{ex}");
                }
            }
        }

        protected void CheckAcceptList(FastList<Socket> acceptList)
        {
            Socket client;
            for (int i = 0; i < acceptList.Count; i++)
            {
                client = acceptList[i];
                if (!client.Connected)
                {
                    client.Close();
                    acceptList.RemoveAt(i);
                    continue;
                }

                if (!client.Poll(performance, SelectMode.SelectRead))
                    continue;
                using (var segment = BufferPool.Take(Config.ReceiveBufferSize))
                {
                    segment.Count = client.Receive(segment.Buffer, 0, segment.Length, SocketFlags.None, out var error);
                    if (segment.Count == 0 | error != SocketError.Success) //当等待10秒超时
                    {
                        client.Close();
                        acceptList.RemoveAt(i);
                        continue;
                    }

                    CheckReconnect(client, segment);
                    acceptList.RemoveAt(i);
                }
            }
        }
    }

    /// <summary>
    /// 默认tcp服务器，当不需要处理NetworkClient对象时可使用
    /// </summary>
    public class TcpServer : TcpServer<ClientPeerBase, SceneBase<ClientPeerBase>>
    {
    }
}